import 'dart:convert';

import 'package:flutter/services.dart';

/// 作者：宋佳宾
/// 日期：2021/4/27
/// 备注：魅族监听器

/// 监听器值模型
typedef ListenerValue<P> = void Function(MzPushListenerTypeEnum type, P params);

/// 监听器类型枚举
enum MzPushListenerTypeEnum {
  MessageReceived,
  onUnRegisterStatus,
  onPushStatus,
  onSubTagsStatus,
  onSubAliasStatus,
  onNotificationClicked,
  onNotificationArrived
}

class MzPushPluginListener {
  /// 监听器列表
  static Set<ListenerValue> listeners = Set();

  /// 添加消息监听
  void addListener(ListenerValue func) {
    listeners.add(func);
  }

  /// 移除消息监听
  void removeListener(ListenerValue func) {
    listeners.remove(func);
  }

  MzPushPluginListener(MethodChannel channel) {
    // 绑定监听器
    channel.setMethodCallHandler((methodCall) async {
      // 解析参数
      Map<dynamic, dynamic> arguments = methodCall.arguments;

      switch (methodCall.method) {
        case 'onListener':
          // 获得原始类型和参数
          String typeStr = arguments['type'].toString();
          var params = arguments['params'] != null ? arguments['params'] : null;

          // 封装回调类型和参数
          MzPushListenerTypeEnum type;

          // 初始化类型
          for (var item in MzPushListenerTypeEnum.values) {
            var es = item.toString().split(".");
            if (es[es.length - 1] == typeStr) {
              type = item;
              break;
            }
          }

          // 没有找到类型就返回
          if (type == null) {
            throw MissingPluginException();
          }

          // 回调触发
          switch (type) {
            case MzPushListenerTypeEnum.MessageReceived:
              params = jsonDecode(params);
              break;
            default:
              break;
          }

          for (var item in listeners) {
            item(type, params);
          }

          break;
        default:
          throw MissingPluginException();
      }
    });
  }
}
